import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }

public class Test {
    //二叉树的分层遍历
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root==null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int size = 1;
        while(!queue.isEmpty()) {
            List<Integer> newList = new ArrayList<>();
            for(int i=0;i<size;i++) {
                TreeNode cur = queue.poll();
                newList.add(cur.val);
                if(cur.left!=null) {
                    queue.add(cur.left);
                }
                if(cur.right!=null) {
                    queue.add(cur.right);
                }
            }
            list.add(0,newList);
            size = queue.size();
        }

        return list;
    }

    //平衡二叉树
    public int GetMax(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left==null&&root.right==null) {
            return 1;
        }
        int h1 = GetMax(root.left);
        int h2 = GetMax(root.right);
        if(Math.abs(h1-h2)>1|| h1==-1 || h2 ==-1) {
            return -1;
        }else {
            return Math.max(h1,h2) +1;
        }
    }
    public boolean isBalanced(TreeNode root) {
        if(root==null) {
            return true;
        }
        if(GetMax(root)==-1) {
            return false;
        }
        return true;
    }

    //另一颗树的子树
    public boolean isSameTree(TreeNode root1,TreeNode root2) {
        if(root1==null&&root2==null) return true;
        if(root1==null||root2==null) return false;
        if(root1.val!=root2.val) return false;
        return isSameTree(root1.left,root2.left) && isSameTree(root1.right,root2.right);
    }
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root==null) return false;
        if(isSameTree(root,subRoot)) return true;
        if(isSubtree(root.left,subRoot)) return true;
        if(isSubtree(root.right,subRoot)) return true;
        return false;
    }

    //对称二叉树
    public boolean _isSymmetric(TreeNode root1,TreeNode root2) {
        if(root1==null&&root2==null) return true;
        if(root1==null||root2==null) return false;
        if(root1.val!=root2.val) return false;
        return _isSymmetric(root1.left,root2.right) && _isSymmetric(root1.right,root2.left);
    }
    public boolean isSymmetric(TreeNode root) {
        if(root==null) {
            return false;
        }
        return _isSymmetric(root.left,root.right);
    }

    public static void main(String[] args) {

    }
}
